<template>
  <div class="app-container">
    <list :list-obj="listObj" @deleteOne="deleteOne" @cancelOne="cancelOne" @getOne="getOne" />
    <el-dialog
      title="新增计划"
      :visible.sync="dialogVisible"
      width="800px"
      append-to-body
      @close="handleClose"
    >
      <main-form ref="mainForm" :form-data="formData" @submit="submit" />
    </el-dialog>
    <el-dialog
      title="计划详情"
      :visible.sync="detailDialogVisible"
      append-to-body
      fullscreen
    >
      <el-descriptions border>
        <el-descriptions-item
          v-for="(item,index) in plan.plan"
          :key="index"
          :label="item.name"
          label-class-name="labelClass"
          content-class-name="contentClass"
        ><el-button v-if="item.name === '轮灌设备状态'" type="primary" size="mini" @click="showDevice">查看轮灌设备状态</el-button><span v-else>{{ item.value }}</span></el-descriptions-item>
      </el-descriptions>
      <div class="h12" />
      <el-table
        border
        :data="plan.planCtlGroup"
        style="width: 100%"
      >
        <el-table-column
          prop="ctlGroup"
          label="轮灌组"
          align="center"
        />
        <el-table-column
          prop="delay"
          label="延时启动时长（秒）"
          align="center"
        />
        <el-table-column
          prop="val"
          label="灌溉时长（分钟）"
          align="center"
        />
        <el-table-column
          prop="status"
          label="执行状态"
          align="center"
        >
          <template #default="scope">
            <span :class="getPlanStatus(scope.row).class">{{ getPlanStatus(scope.row).name }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <div class="fix-btns">
      <el-button style="flex:1" type="primary" icon="el-icon-plus" @click="add">新增计划</el-button>
      <el-button style="flex:1" type="success" icon="el-icon-refresh" @click="refresh">刷新计划</el-button>
    </div>
    <el-dialog
      v-el-drag-dialog
      :title="deviceContainerTitle"
      :visible.sync="deviceContainerVisible"
      append-to-body
      fullscreen
    >
      <span
        v-if="currentDevice"
        slot="title"
        class="device-header"
      >
        <el-image
          class="device-image"
          :src="getDeviceImage(currentDevice)"
          :fit="fit"
        />
        {{ currentDevice.name + ' —— ' + currentDevice.serialno }}
      </span>
      <dg />
    </el-dialog>
  </div>
</template>

<script>
import MainForm from './components/main-form'
import List from './components/list'
import Dg from '@/components/Device/Dg'
import { getAll, addOne, cancelOne, deleteOne } from '@/api/plan'
import CommonMixin from '@/mixin/CommonMixin'
import { formatPlanData, formatPlanDataForQf, getPlanStatus, getDeviceImage } from '@/utils/device'
import { dclassCodeMap } from '@/utils/constant'
import { mapGetters } from 'vuex'
import { getCurrentDate } from '@/utils'
export default {
  components: {
    MainForm,
    List,
    Dg
  },
  mixins: [CommonMixin],
  props: {
    planDrawerVisible: {
      type: Boolean,
      default() {
        return true
      }
    }
  },
  inject: ['reload'],
  data() {
    return {
      dialogVisible: false,
      currentDevice: null,
      deviceContainerVisible: false,
      deviceContainerTitle: '',
      fit: 'fill',
      formData: {
        serialno: '',
        name: '',
        starttime: ''
      },
      serialno: this.$store.getters.devices.filter((val) => {
        return +val.product_type === +dclassCodeMap.dg
      })[0].serialno,
      detailDialogVisible: false,
      plan: []
    }
  },
  computed: {
    ...mapGetters(['devicesObj', 'devices', 'uid', 'user', 'project'])
  },
  watch: {
    planDrawerVisible(newVal, oldVal) {
      if (newVal) {
        this.getList()
      }
    },
    serialno: {
      handler(newVal) {
        if (newVal) {
          this.formData.serialno = newVal
        }
      },
      immediate: true
    }
  },
  methods: {
    getDeviceImage(device) {
      return getDeviceImage(device)
    },
    showDevice() {
      this.currentDevice = this.devices.filter((val) => {
        return +val.product_type === +dclassCodeMap.dg
      })[0]
      this.$store.commit('device/SET_CURRENT_DEVICE', this.currentDevice)
      this.$store.commit('device/SET_CURRENT_DEVICE_SHOW', true)
      this.deviceContainerTitle = this.currentDevice.name
      this.deviceContainerVisible = true
    },
    handleClose() {
      this.dialogVisible = false
      this.reset()
      this.$refs.mainForm.resetCells()
    },
    submit(formData) {
      console.log(formData)
      return
      let data = {}
      if (this.project.type === 'qf') {
        data = formatPlanDataForQf(formData, this.uid)
      } else {
        data = formatPlanData(formData, this.uid)
      }
      this.addOne(data)
    },
    async getList() {
      const listObj = await getAll(this.serialno)
      this.listObj = listObj
    },
    addOne(formData) {
      addOne(formData).then(res => {
        if (res.errorCode === 0) {
          this.$message({ message: res.msg, type: 'success', showClose: true })
          this.dialogVisible = false
          this.reset()
          this.getList()
        }
      })
    },
    deleteOne(row) {
      deleteOne(row.id).then(res => {
        if (res.errorCode === 0) {
          this.$message({ message: res.msg, type: 'success', showClose: true })
          this.getList()
        }
      })
    },
    cancelOne(row) {
      cancelOne(row.id).then(res => {
        if (res.errorCode === 0) {
          this.$message({ message: res.msg, type: 'success', showClose: true })
          this._afterSubmit()
        }
      })
    },
    getOne(row) {
      this.plan = this.formatPlanDataShow(row)
      this.detailDialogVisible = true
    },
    add() {
      this.formData.name = '轮灌计划' + getCurrentDate()
      this.dialogVisible = true
    },
    refresh() {
      getAll(this.serialno).then((res) => {
        this.listObj = res
        this.$notify.success(res.msg)
      })
    },
    formatPlanDataShow(formData) {
      const plan = [
        { name: '计划名称', value: formData.name },
        { name: '轮灌设备', value: this.devicesObj[formData.serialno].name },
        { name: '轮灌设备编号', value: formData.serialno },
        { name: '轮灌设备状态', value: formData.createdAt },
        { name: '开始执行时间', value: formData.val },
        { name: '执行状态', value: getPlanStatus(formData).name }
      ]
      const rr = new Map()
      const planCtlGroup = formData.devices.filter((item) =>
        !rr.has(item.ctlGroup) && rr.set(item.ctlGroup, 1)
      )

      return {
        plan,
        planCtlGroup
      }
    },
    getPlanStatus(item) {
      return getPlanStatus(item)
    },
    reset() {
      this.formData = {
        serialno: this.serialno,
        name: '',
        starttime: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  position:relative;
  height:94vh;
}
.fix-btns{
  position:fixed;
  display:flex;
  width:450px;
  bottom:12px;
  right:12px;
  background:#fff;
}
</style>
